package com.fanshuai.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class NettyWebsocketServer {
    ExecutorService executorService = Executors.newSingleThreadExecutor();

    AtomicInteger run = new AtomicInteger(0);
    public void init() {
        if (run.compareAndSet(0, 1)) {
            NioEventLoopGroup boss = new NioEventLoopGroup(1); //acceptor设置线程数为1
            NioEventLoopGroup child = new NioEventLoopGroup(); //io handler默认线程数为 2 * cpu

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, child)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.SO_BACKLOG, 1024);

            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new LoggingHandler("DEBUG"));
                    pipeline.addLast(new HttpServerCodec());
                    pipeline.addLast(new HttpObjectAggregator(65536));
                    pipeline.addLast(new ChunkedWriteHandler());
                    pipeline.addLast(new NettyWebsocketHandler());
                }
            });

            try {
                Channel channel = serverBootstrap.bind(8081).sync().channel();
                log.info("netty websocket server started");
                channel.closeFuture().sync();
            } catch (Exception e) {
                log.error("" + e);
            } finally {
                boss.shutdownGracefully();
                child.shutdownGracefully();

                run.compareAndSet(1, 0);
            }
        }
    }

    public void start() {
        executorService.execute(this::init);
    }
}
